<template>
  <div class="ptz-control">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>PTZ控制</span>
          <div class="header-controls">
            <el-select v-model="selectedChannel" placeholder="选择通道" @change="onChannelChange">
              <el-option
                v-for="channel in channels"
                :key="channel.id"
                :label="channel.name"
                :value="channel.id"
              />
            </el-select>
          </div>
        </div>
      </template>
      
      <div class="ptz-container">
        <!-- 视频预览 -->
        <div class="video-preview">
          <div class="video-wrapper">
            <video 
              ref="videoRef"
              controls 
              autoplay
              muted
              class="video-player"
            >
              <source :src="streamUrl" type="application/x-mpegURL">
              您的浏览器不支持视频播放
            </video>
          </div>
        </div>
        
        <!-- PTZ控制面板 -->
        <div class="control-panel">
          <!-- 方向控制 -->
          <div class="direction-control">
            <h4>方向控制</h4>
            <div class="direction-pad">
              <div class="direction-row">
                <el-button 
                  class="direction-btn" 
                  @mousedown="startMove('up-left')"
                  @mouseup="stopMove"
                  @mouseleave="stopMove"
                >
                  ↖
                </el-button>
                <el-button 
                  class="direction-btn" 
                  @mousedown="startMove('up')"
                  @mouseup="stopMove"
                  @mouseleave="stopMove"
                >
                  ↑
                </el-button>
                <el-button 
                  class="direction-btn" 
                  @mousedown="startMove('up-right')"
                  @mouseup="stopMove"
                  @mouseleave="stopMove"
                >
                  ↗
                </el-button>
              </div>
              <div class="direction-row">
                <el-button 
                  class="direction-btn" 
                  @mousedown="startMove('left')"
                  @mouseup="stopMove"
                  @mouseleave="stopMove"
                >
                  ←
                </el-button>
                <el-button class="direction-btn center-btn" @click="stopMove">
                  停止
                </el-button>
                <el-button 
                  class="direction-btn" 
                  @mousedown="startMove('right')"
                  @mouseup="stopMove"
                  @mouseleave="stopMove"
                >
                  →
                </el-button>
              </div>
              <div class="direction-row">
                <el-button 
                  class="direction-btn" 
                  @mousedown="startMove('down-left')"
                  @mouseup="stopMove"
                  @mouseleave="stopMove"
                >
                  ↙
                </el-button>
                <el-button 
                  class="direction-btn" 
                  @mousedown="startMove('down')"
                  @mouseup="stopMove"
                  @mouseleave="stopMove"
                >
                  ↓
                </el-button>
                <el-button 
                  class="direction-btn" 
                  @mousedown="startMove('down-right')"
                  @mouseup="stopMove"
                  @mouseleave="stopMove"
                >
                  ↘
                </el-button>
              </div>
            </div>
          </div>
          
          <!-- 缩放控制 -->
          <div class="zoom-control">
            <h4>缩放控制</h4>
            <div class="zoom-buttons">
              <el-button 
                type="primary" 
                @mousedown="startZoom('in')"
                @mouseup="stopZoom"
                @mouseleave="stopZoom"
              >
                放大 +
              </el-button>
              <el-button 
                @mousedown="startZoom('out')"
                @mouseup="stopZoom"
                @mouseleave="stopZoom"
              >
                缩小 -
              </el-button>
            </div>
          </div>
          
          <!-- 速度控制 -->
          <div class="speed-control">
            <h4>移动速度</h4>
            <el-slider 
              v-model="moveSpeed" 
              :min="1" 
              :max="10" 
              :step="1"
              show-stops
              show-tooltip
            />
          </div>
          
          <!-- 预设位控制 -->
          <div class="preset-control">
            <h4>预设位管理</h4>
            <div class="preset-list">
              <div 
                v-for="preset in presets" 
                :key="preset.token"
                class="preset-item"
              >
                <span>{{ preset.name }}</span>
                <div class="preset-actions">
                  <el-button size="small" @click="gotoChannelPreset(preset.token)">
                    调用
                  </el-button>
                  <el-button size="small" type="danger" @click="deletePreset(preset.token)">
                    删除
                  </el-button>
                </div>
              </div>
            </div>
            <div class="preset-add">
              <el-input 
                v-model="newPresetName" 
                placeholder="预设位名称" 
                style="width: 150px; margin-right: 10px;"
              />
              <el-button type="primary" @click="addPresetPosition">
                添加预设位
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { ptzControl, getPresets, addPreset, removePreset, gotoPreset } from '@/api/ptz'
import { getStreamUrl } from '@/api/streaming'
import { getAllChannels } from '@/api/channel'

const selectedChannel = ref('')
const streamUrl = ref('')
const videoRef = ref(null)
const moveSpeed = ref(5)
const newPresetName = ref('')

const channels = ref([])
const presets = ref([])

let moveTimer = null
let zoomTimer = null

// 加载通道列表
const loadChannels = async () => {
  try {
    const response = await getAllChannels()
    channels.value = response.data || []
  } catch (error) {
    ElMessage.error('加载通道列表失败')
  }
}

// 加载预设位列表
const loadPresets = async () => {
  if (!selectedChannel.value) return
  
  try {
    const response = await getPresets(selectedChannel.value)
    presets.value = response.data || []
  } catch (error) {
    ElMessage.error('加载预设位失败')
  }
}

// 通道变化处理
const onChannelChange = async () => {
  if (!selectedChannel.value) return
  
  try {
    // 获取流媒体URL
    const response = await getStreamUrl(selectedChannel.value, 'hls')
    streamUrl.value = response.data || ''
    
    // 加载预设位
    await loadPresets()
  } catch (error) {
    ElMessage.error('获取流媒体地址失败')
  }
}

// 开始移动
const startMove = (direction) => {
  if (!selectedChannel.value) {
    ElMessage.warning('请先选择通道')
    return
  }
  
  const command = {
    action: 'move',
    direction: direction,
    speed: moveSpeed.value
  }
  
  // 立即执行一次
  executePTZCommand(command)
  
  // 设置定时器持续执行
  moveTimer = setInterval(() => {
    executePTZCommand(command)
  }, 100)
}

// 停止移动
const stopMove = () => {
  if (moveTimer) {
    clearInterval(moveTimer)
    moveTimer = null
  }
  
  if (selectedChannel.value) {
    executePTZCommand({ action: 'stop' })
  }
}

// 开始缩放
const startZoom = (direction) => {
  if (!selectedChannel.value) {
    ElMessage.warning('请先选择通道')
    return
  }
  
  const command = {
    action: 'zoom',
    direction: direction,
    speed: moveSpeed.value
  }
  
  executePTZCommand(command)
  
  zoomTimer = setInterval(() => {
    executePTZCommand(command)
  }, 100)
}

// 停止缩放
const stopZoom = () => {
  if (zoomTimer) {
    clearInterval(zoomTimer)
    zoomTimer = null
  }
  
  if (selectedChannel.value) {
    executePTZCommand({ action: 'stop' })
  }
}

// 执行PTZ命令
const executePTZCommand = async (command) => {
  try {
    await ptzControl(selectedChannel.value, command)
  } catch (error) {
    console.error('PTZ控制失败:', error)
  }
}

// 调用预设位
const gotoChannelPreset = async (presetToken) => {
  try {
    await gotoPreset(selectedChannel.value, presetToken)
    ElMessage.success('预设位调用成功')
  } catch (error) {
    ElMessage.error('预设位调用失败')
  }
}

// 删除预设位
const deletePreset = async (presetToken) => {
  try {
    await removePreset(selectedChannel.value, presetToken)
    ElMessage.success('预设位删除成功')
    await loadPresets()
  } catch (error) {
    ElMessage.error('预设位删除失败')
  }
}

// 添加预设位
const addPresetPosition = async () => {
  if (!newPresetName.value.trim()) {
    ElMessage.warning('请输入预设位名称')
    return
  }
  
  try {
    await addPreset(selectedChannel.value, { name: newPresetName.value.trim() })
    ElMessage.success('预设位添加成功')
    newPresetName.value = ''
    await loadPresets()
  } catch (error) {
    ElMessage.error('预设位添加失败')
  }
}

onMounted(() => {
  loadChannels()
})

onUnmounted(() => {
  stopMove()
  stopZoom()
})
</script>

<style scoped>
.ptz-control {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ptz-container {
  display: flex;
  gap: 20px;
}

.video-preview {
  flex: 2;
}

.video-wrapper {
  position: relative;
  background: #000;
  border-radius: 8px;
  overflow: hidden;
}

.video-player {
  width: 100%;
  height: 400px;
  object-fit: contain;
}

.control-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.direction-control h4,
.zoom-control h4,
.speed-control h4,
.preset-control h4 {
  margin: 0 0 10px 0;
  color: #333;
}

.direction-pad {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.direction-row {
  display: flex;
  gap: 5px;
  justify-content: center;
}

.direction-btn {
  width: 50px;
  height: 50px;
  font-size: 18px;
  font-weight: bold;
}

.center-btn {
  background-color: #f56c6c;
  border-color: #f56c6c;
  color: white;
}

.zoom-buttons {
  display: flex;
  gap: 10px;
}

.zoom-buttons .el-button {
  flex: 1;
}

.preset-list {
  max-height: 200px;
  overflow-y: auto;
  margin-bottom: 10px;
}

.preset-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 5px;
}

.preset-actions {
  display: flex;
  gap: 5px;
}

.preset-add {
  display: flex;
  align-items: center;
}
</style>